﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using K3R.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Data;

namespace K3R.Logic {
	[DataContract]
	public class StateCode {
		#region Properties
		[DataMember(Name = "code")] public string Code { get; set; }
		[DataMember(Name = "name")] public string Name { get; set; }
		#endregion

		public StateCode() { }

		#region Static
		public static List<StateCode> List() {
			using (var conn = new Connection(Settings.ConnectionString, "state_code_list")) {
				return ListReader(conn.ExecuteReader());
			}
		}

		public static StateCode Load(string code) {
			StateCode stateCode = null;
			using (var conn = new Connection("state_code_load")) {
				conn.AddParameter("@code", code);

				var dr = conn.ExecuteReader(CommandBehavior.SingleRow);
				if (dr.Read())
					stateCode = Reader(dr);
			}
			return stateCode;
		}

		public static bool Exists(string code) {
			using (var conn = new Connection(Settings.ConnectionString, "state_code_exists")) {
				conn.AddParameter("@code", code);
				return conn.ExecuteNonQuery<bool>("@exists", SqlDbType.Bit);
			}
		}

		public static void BindDropDownList(DropDownList ddl, bool optional, string defaultValue) {
			ddl.Items.Clear();
			ddl.AppendDataBoundItems = true;

			if (optional)
				ddl.Items.Add("Select One");

			ddl.DataSource = List();
			ddl.DataValueField = "Code";
			ddl.DataTextField = "Name";
			ddl.DataBind();

			if (defaultValue != null)
				foreach (ListItem li in ddl.Items)
					if (li.Value == defaultValue) {
						li.Selected = true;
						break;
					}
		}

		public static void BindDropDownList(DropDownList ddl, bool optional) {
			BindDropDownList(ddl, optional, null);
		}

		public static void BindDropDownList(DropDownList ddl, string defaultValue) {
			BindDropDownList(ddl, false, defaultValue);
		}

		public static void BindDropDownList(DropDownList ddl) {
			BindDropDownList(ddl, false, null);
		}
		#endregion

		#region Conversion
		protected static StateCode Reader(SqlDataReader dr) {
			return new StateCode {
				Code = dr["code"].ToString(),
				Name = dr["name"].ToString()
			};
		}

		protected static List<StateCode> ListReader(SqlDataReader dr) {
			var list = new List<StateCode>();

			while (dr.Read())
				list.Add(Reader(dr));

			return list;
		}
		#endregion
	}
}
